package com.iot.http;

import com.iot.compont.ServerNetwork;
import com.iot.gateway.GatewayEntity;
import com.iot.messaage.FromDeviceMessageContext;
import com.iot.network.HttpDeviceSession;
import com.iot.test.TestDeviceMessageDecoder;
import com.iot.topic.DeviceMessage;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Administrator
 */
public class HttpServerNetwork implements ServerNetwork {
    public HttpServerRequest serverRequest;
    private Vertx vertx;
    private Collection<HttpServer> instances;
    public GatewayEntity gatewayEntity;
//    String networkType = GatewayServerEnum.HTTP.name();

    @Override
    public HttpServerNetwork createServer(GatewayEntity gatewayEntity) {
        this.gatewayEntity = gatewayEntity;
        vertx = Vertx.vertx();
        int instance = Math.max(2, Runtime.getRuntime().availableProcessors());
        instances = new ArrayList<>(instance);
        SocketAddress socketAddress = SocketAddress.inetSocketAddress(gatewayEntity.getProd(), gatewayEntity.getHost());
        for (int i = 0; i < instance; i++) {
            instances.add(vertx.createHttpServer());
        }
        for (HttpServer httpServer : instances) {
            {
                httpServer.requestHandler(this::handleConnection);
                vertx.nettyEventLoopGroup().execute(() -> httpServer.
                        listen(socketAddress, result -> {
                            if (result.succeeded()) {
                                //这里将存储成功的网关
                            } else {

                            }
                        }));
                httpServer.exceptionHandler(err -> {
                });
            }
        }
        return this;
    }

    @Override
    public Runnable cloneServer() {
        return () -> {
            for (HttpServer httpServer : instances) {
                httpServer.close(httpServerAsyncResult -> {
                    if (httpServerAsyncResult.succeeded()) {
                        //这里将网关进行关闭
                    }
                });
            }
            instances.clear(); // 清除列表
        };
    }

    public void handleConnection(HttpServerRequest httpServerRequest) {
        HttpDeviceSession session = new HttpDeviceSession(httpServerRequest);
        TestDeviceMessageDecoder testDeviceMessageDecoder = new TestDeviceMessageDecoder();
        DeviceMessage decode = testDeviceMessageDecoder.decode(FromDeviceMessageContext.of(session));

        HttpMethod method = httpServerRequest.method();
        String deviceId = decode.getDeviceId().toString();


    }
}
